package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.enums.CustomerFundBindLevelTypeEnum;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.customer.CustomerInfo;
import com.probox.common.entity.domain.customer.CustomerTaskInfo;
import com.probox.common.entity.domain.customer.CustomerTaskInfoRecord;
import com.probox.common.entity.domain.system.SysDictData;
import com.probox.common.entity.mapper.customer.CustomerTaskInfoMapper;
import com.probox.common.entity.mapper.customer.CustomerTaskInfoRecordMapper;
import com.probox.common.entity.mapper.product.ProductInfoMapper;
import com.probox.common.entity.service.customer.ICustomerFundService;
import com.probox.common.entity.service.customer.ICustomerTaskInfoRecordService;
import com.probox.common.entity.service.customer.ICustomerTaskInfoService;
import com.probox.common.entity.service.system.ISysDictDataService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 任务列Service业务层处理
 *
 * @author usoft
 * @date 2022-09-30
 */
@Service
@Transactional
public class CustomerTaskInfoServiceImpl extends ServiceImpl<CustomerTaskInfoMapper, CustomerTaskInfo> implements ICustomerTaskInfoService {
    @Autowired
    private CustomerTaskInfoMapper customerTaskInfoMapper;

    @Autowired
    private CustomerTaskInfoRecordMapper customerTaskInfoRecordMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private ICustomerTaskInfoRecordService customerTaskInfoRecordService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ICustomerFundService customerFundService;

    /**
     * 查询任务列
     *
     * @param taskId 任务列ID
     * @return 任务列
     */
    @Override
    public CustomerTaskInfo selectCustomerTaskInfoById(Long taskId) {
        CustomerTaskInfo vo = this.getById(taskId);

        if (ObjectUtils.isNotEmpty(vo.getProductId()))
            vo.setProducName(productInfoMapper.selectById(vo.getProductId()).getProductName());
        return vo;
    }

    /**
     * 查询任务列列表
     *
     * @param customerTaskInfo 任务列
     * @return 任务列
     */
    @Override
    public List<CustomerTaskInfo> queryList(CustomerTaskInfo customerTaskInfo) {
        QueryWrapper<CustomerTaskInfo> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getTaskId())) && customerTaskInfo.getTaskId() != null) {
            queryWrapper.eq("task_id", customerTaskInfo.getTaskId());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getTaskCode())) && customerTaskInfo.getTaskCode() != null) {
            queryWrapper.eq("task_code", customerTaskInfo.getTaskCode());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getTaskName())) && customerTaskInfo.getTaskName() != null) {
            queryWrapper.like("task_name", customerTaskInfo.getTaskName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getTaskDesc())) && customerTaskInfo.getTaskDesc() != null) {
            queryWrapper.eq("task_desc", customerTaskInfo.getTaskDesc());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getTaskIcon())) && customerTaskInfo.getTaskIcon() != null) {
            queryWrapper.eq("task_icon", customerTaskInfo.getTaskIcon());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getStartDate())) && customerTaskInfo.getStartDate() != null) {
            queryWrapper.eq("start_date", customerTaskInfo.getStartDate());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getEndDate())) && customerTaskInfo.getEndDate() != null) {
            queryWrapper.eq("end_date", customerTaskInfo.getEndDate());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getTaskBrief())) && customerTaskInfo.getTaskBrief() != null) {
            queryWrapper.eq("task_brief", customerTaskInfo.getTaskBrief());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getIsShow())) && customerTaskInfo.getIsShow() != null) {
            queryWrapper.eq("is_show", customerTaskInfo.getIsShow());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getScore())) && customerTaskInfo.getScore() != null) {
            queryWrapper.eq("score", customerTaskInfo.getScore());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getExpValue())) && customerTaskInfo.getExpValue() != null) {
            queryWrapper.eq("exp_value", customerTaskInfo.getExpValue());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getServiceItemId())) && customerTaskInfo.getServiceItemId() != null) {
            queryWrapper.eq("service_item_id", customerTaskInfo.getServiceItemId());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getCardId())) && customerTaskInfo.getCardId() != null) {
            queryWrapper.eq("card_id", customerTaskInfo.getCardId());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getCouponId())) && customerTaskInfo.getCouponId() != null) {
            queryWrapper.eq("coupon_id", customerTaskInfo.getCouponId());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getProductId())) && customerTaskInfo.getProductId() != null) {
            queryWrapper.eq("product_id", customerTaskInfo.getProductId());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getTaskSort())) && customerTaskInfo.getTaskSort() != null) {
            queryWrapper.eq("task_sort", customerTaskInfo.getTaskSort());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getDataStatus())) && customerTaskInfo.getDataStatus() != null) {
            queryWrapper.eq("data_status", customerTaskInfo.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getCreateUser())) && customerTaskInfo.getCreateUser() != null) {
            queryWrapper.eq("create_user", customerTaskInfo.getCreateUser());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getCreateName())) && customerTaskInfo.getCreateName() != null) {
            queryWrapper.eq("create_name", customerTaskInfo.getCreateName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getUpdateUser())) && customerTaskInfo.getUpdateUser() != null) {
            queryWrapper.eq("update_user", customerTaskInfo.getUpdateUser());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerTaskInfo.getUpdateName())) && customerTaskInfo.getUpdateName() != null) {
            queryWrapper.eq("update_name", customerTaskInfo.getUpdateName());
        }

        queryWrapper.orderByDesc("task_id");

        List<CustomerTaskInfo> list = customerTaskInfoMapper.selectList(queryWrapper);
        CustomerTaskInfo vo = null;
        Iterator<CustomerTaskInfo> it = list.iterator();
        while (it.hasNext()) {
            vo = it.next();
            QueryWrapper<CustomerTaskInfoRecord> query = Wrappers.query();
            query.eq("task_id", vo.getTaskId());
            long count = customerTaskInfoRecordMapper.selectCount(query);
            vo.setCompleted(count);

            if (ObjectUtils.isNotEmpty(vo.getProductId()))
                vo.setProducName(productInfoMapper.selectById(vo.getProductId()).getProductName());
        }


        return list;


    }

    @Override
    public List<CustomerTaskInfo> showAppletList() {
        QueryWrapper<CustomerTaskInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("is_show", DataStatus.valid.getKey());
        queryWrapper.eq("data_status", DataStatus.valid.getKey());
        queryWrapper.last(" and start_date<=SYSDATE() and end_date>=SYSDATE() order by task_sort");
        List<CustomerTaskInfo> list = customerTaskInfoMapper.selectList(queryWrapper);
        CustomerTaskInfoRecord record = new CustomerTaskInfoRecord();
        record.setCustomerUid(SecurityUtils.getCustomerUid());
        record.setIsShow(DataStatus.valid.getKey());
        List<CustomerTaskInfoRecord> recordList = customerTaskInfoRecordService.queryList(record);
        Map<String, String> map = new HashMap<>();
        for (CustomerTaskInfoRecord cir : recordList) {
            map.put(cir.getTaskCode(), cir.getCardName());
        }
        for (CustomerTaskInfo ci : list) {
            ci.setCompleted(0L);
            if (map.containsKey(ci.getTaskCode())) {
                ci.setCompleted(1L);
            }
            SysDictData dictData = sysDictDataService.selectDict("sys_task", ci.getTaskCode());
            if (dictData != null)
                ci.setTaskPage(dictData.getRemark());
        }
        return list;
    }

    /**
     * 新增任务列
     *
     * @param customerTaskInfo 任务列
     * @return 结果
     */
    @Override
    public boolean insertCustomerTaskInfo(CustomerTaskInfo customerTaskInfo) {
        if (queryCode(null, customerTaskInfo.getTaskCode()) > 0) throw new BaseException("该任务代码已被使用");
        customerTaskInfo.setCreateUser(SecurityUtils.getUserId());
        customerTaskInfo.setCreateName(SecurityUtils.getUsername());
        customerTaskInfo.setCreateTime(DateUtils.getNowDate());
        return this.save(customerTaskInfo);

    }

    /**
     * 修改任务列
     *
     * @param customerTaskInfo 任务列
     * @return 结果
     */
    @Override
    public boolean updateCustomerTaskInfo(CustomerTaskInfo customerTaskInfo) {
        if (ObjectUtil.isNotEmpty(customerTaskInfo.getTaskName()) && queryCode(customerTaskInfo.getTaskId(), customerTaskInfo.getTaskCode()) > 0)
            throw new BaseException("该任务代码已被使用");

        UpdateWrapper<CustomerTaskInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("task_id", customerTaskInfo.getTaskId());
        updateWrapper.set("score", customerTaskInfo.getScore());
        updateWrapper.set("exp_value", customerTaskInfo.getExpValue());
        updateWrapper.set("service_item_id", customerTaskInfo.getServiceItemId());
        updateWrapper.set("card_id", customerTaskInfo.getCardId());
        updateWrapper.set("coupon_id", customerTaskInfo.getCouponId());
        updateWrapper.set("product_id", customerTaskInfo.getProductId());
        updateWrapper.set("task_Sort", customerTaskInfo.getTaskSort());
        updateWrapper.set("task_Brief", customerTaskInfo.getTaskBrief());
        updateWrapper.set("task_Icon", customerTaskInfo.getTaskIcon());
        updateWrapper.set("start_Date", customerTaskInfo.getStartDate());
        updateWrapper.set("end_date", customerTaskInfo.getEndDate());
        updateWrapper.set("task_Desc", customerTaskInfo.getTaskDesc());
        updateWrapper.set("UPDATE_User", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);

    }

    /**
     * 批量删除任务列
     *
     * @param taskIds 需要删除的任务列ID
     * @return 结果
     */
    @Override
    public boolean deleteCustomerTaskInfoByIds(Long[] taskIds) {
        return this.removeByIds(Arrays.asList(taskIds));
    }

    @Override
    public boolean finishTask(CustomerInfo customerInfo, String code) {
        //如果已经完成了，就返回true
        if (customerTaskInfoRecordService.queryCustomerTask(code,customerInfo.getCustomerUid()).size()>0){
            return true;
        }
        QueryWrapper<CustomerTaskInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("task_code", code);
        queryWrapper.last(" and  data_status=1 and start_date<=SYSDATE() and end_date>=SYSDATE() order by task_id desc limit 1 ");
        CustomerTaskInfo taskInfo = customerTaskInfoMapper.selectOne(queryWrapper);
        if (taskInfo != null){
            if (taskInfo.getScore() != null && taskInfo.getScore()>0){
                com.probox.customer.api.domain.CustomerFundVo customerFundVo = new com.probox.customer.api.domain.CustomerFundVo();
                customerFundVo.setCustomerUid(customerInfo.getCustomerUid());
                customerFundVo.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
                customerFundVo.setScore(taskInfo.getScore());
                customerFundVo.setStatus(DataStatus.valid.getKey());
                customerFundVo.setRemark(taskInfo.getTaskName());
                customerFundVo.setBizTime(new Date());
                customerFundService.addCustomerFund(customerFundVo);
            }
            CustomerTaskInfoRecord record = new CustomerTaskInfoRecord();
            BeanUtils.copyProperties(taskInfo,record);
            record.setCustomerUid(customerInfo.getCustomerUid());
            record.setCreateTime(new Date());
            record.setCreateName(customerInfo.getCustomerName());
            record.setCreateUser(customerInfo.getCustomerUid());
            record.setDataStatus(DataStatus.valid.getKey());
            return customerTaskInfoRecordService.save(record);
        }
        return false;
    }


    public Integer queryCode(Long uid, String code) {
        QueryWrapper<CustomerTaskInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_code", code);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (ObjectUtil.isNotEmpty(uid)) {
            queryWrapper.ne("task_id", uid);
        }
        return customerTaskInfoMapper.selectCount(queryWrapper);
    }

}
